package calao.client.ui;

import com.google.gwt.user.client.ui.TextBox;

public class NumberBox 
extends TextBox
implements Validatable
{
	
	final boolean integersOnly;
	
	boolean emptyAllowed = false;
	
	NumberFormat format;
	
	public NumberBox()
	{
		this(false);
	}

	public NumberBox(boolean integersOnly)
	{
		this.integersOnly = integersOnly;
		this.format = Format.NUMBER;
	}

	public NumberBox(NumberFormat format)
	{
		this(false);
		this.format = format;
	}

	public int getInt() 
	{
		return Integer.parseInt(getText().replaceAll(" ", ""));
	}
	
	public int getInt(int defaultValue) 
	{
		return isEmpty()? defaultValue : Integer.parseInt(getText().replaceAll(" ", ""));
	}

	public double getDouble()
	{
		return format.parse(getText().replaceAll(" ", ""));
	}

	public double getDouble(double defaultValue)
	{
		return isEmpty()? defaultValue : format.parse(getText());
	}

	public void validate() throws InvalidInputException 
	{
		try {
			if (emptyAllowed && isEmpty()) ;
			else if (integersOnly) getInt();
			else getDouble();
			removeStyleName(Styles.INVALID);
		}
		catch (Exception e) {
			addStyleName(Styles.INVALID);
			throw new InvalidInputException();
		}
	}
	
	public void setNumber(int value)
	{
		setText(Integer.toString(value));
	}
	
	public void setNumber(double value)
	{
		setText(format.format(value));
	}
	
	public void setEmptyAllowed(boolean allowed)
	{
		this.emptyAllowed = allowed;
	}
	
	public boolean isEmpty()
	{
		return getText()==null || getText().length()==0;
	}
	
	public void clear()
	{
		setText("");
	}
	
	public void setFormat(NumberFormat format)
	{
		this.format = format;
	}

}
